/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.impl;

import com.ivanbiz.dao.NotaDAO;
import com.ivanbiz.model.Barang;
import com.ivanbiz.model.HibernateUtil;
import com.ivanbiz.model.Hutang;
import com.ivanbiz.model.ItemNota;
import com.ivanbiz.model.Nota;
import java.util.Date;
import javax.swing.JOptionPane;
import org.hibernate.Session;

/**
 *
 * @author User
 */
public class NotaDAOImpl extends GenericDAOImpl implements NotaDAO {

    public void saveTransaksiPenjualan(Nota nota, double totalHarga, long tempo) throws Exception {
        try {
            HibernateUtil.beginTransaction();
            Session session = HibernateUtil.getSession();           
            Barang barang = null;
            for (int x = 0; x < nota.getItemNota().size(); x++) {
                ItemNota n = (ItemNota) nota.getItemNota().get(x);
                barang = (Barang) session.load(Barang.class, n.getBarang().getId());
                barang.setStock(barang.getStock() - n.getJumlah());
                session.update(barang);
                session.flush();
                if (barang.getStock() < 0) {
                    JOptionPane.showMessageDialog(null, "Cek Stock Barang " + barang.getNama() + " dan ulangi transaksi kembali!!!");
                    Integer.parseInt("y");
                }
            }

            if (nota.getStatusPembayaran().equals("Kredit")) {
                Hutang hutang = new Hutang();
                Date date = new Date();
                date.setDate((int) (date.getDate() + tempo));
                date.setHours(0);
                date.setMinutes(0);
                date.setSeconds(0);
                hutang.setJatuhTempo(date);
                hutang.setNota(nota);
                hutang.setSisaHutang(totalHarga);
                session.save(hutang);
            }
            session.save(nota);
            HibernateUtil.commitTransaction();
        } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
            throw e;
        } finally {
            HibernateUtil.closeSession();
        }

    }
}
